package com.mercycrazy.recruit.util;

import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * MD5 加密工具类
 *
 * @author <a href="mailto:1443424326@qq.com">mercycrazy</a>
 * @since 2023-01-18
 */
public class MD5Util {

    /**
     * MD5 混合加密
     *
     * @param data: 待加密字符串
     * @param slat: 盐, 用于混合md5加密
     */
    public static String encrypt(String data, String slat) {
        String base = data + slat;
        return DigestUtils.md5DigestAsHex(base.getBytes());
    }

    /**
     * 获取定长 MD5 加密字符串
     *
     * @param data 待加密字符串
     */
    public static String MD5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
            }
            return sb.toString().toUpperCase();
        } catch (Exception ignored) {
        }
        return null;
    }
}
